package com.huiyeji.hui.auth;

import com.huiyeji.hui.entity.User;
import com.huiyeji.hui.exception.AuthException;

import javax.servlet.http.HttpSession;

/**
 * @author zhaoduo
 * 认证器
 */
public class Authenticator {

    private static final String LICENSE_KEY = "155484876521-license";

    private Authenticator(){}

    private static final class AuthenticatorHolder {
        static final Authenticator AUTHENTICATOR = new Authenticator();
    }

    public static Authenticator getInstance(){
        return AuthenticatorHolder.AUTHENTICATOR;
    }

    /**
     * 授权
     * @param session session
     * @param user user
     * @param licenses 权限
     */
    public void authorized(HttpSession session,User user,License...licenses){
        if (licenses != null && licenses.length>0){
            StringBuilder stringBuilder = new StringBuilder();
            for (License license : licenses) {
                stringBuilder.append(license.toString()).append(",");
            }
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
            session.setAttribute(LICENSE_KEY,stringBuilder.toString());
        }
        session.setAttribute("user",user);
    }

    /**
     * 检查许可证,检查通过则返回该用户实例,否则抛异常
     * @param session session
     * @param licenses 权限
     * @return user
     */
    public User check(HttpSession session,License...licenses){
        if (licenses != null && licenses.length>0 && session != null){
            Object object = session.getAttribute(LICENSE_KEY);
            if (object == null){
                throw new AuthException();
            }
            String licensesString = object.toString();
            for (License license : licenses) {
                if (licensesString.contains(license.toString())) {
                    return (User) session.getAttribute("user");
                }
            }
            throw new AuthException();
        }
        throw new AuthException();
    }
}
